const UserModel = require('../models/userModel');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const register = async (req, res) => {
  try {
    const { username, password, name, contact } = req.body;
    const hashedPassword = await bcrypt.hash(password, 10);
    const user = await UserModel.createUser({
      username,
      password: hashedPassword,
      name,
      contact
    });
    res.status(201).json(user[0]);
  } catch (error) {
    console.error(error); // 打印错误信息，方便调试
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

const login = async (req, res) => {
  try {
    const { username, password } = req.body;
    const user = await UserModel.getUserByUsername(username);
    if (!user) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }
    const token = jwt.sign({ id: user.user_id, username: user.username }, process.env.JWT_SECRET, { expiresIn: '1h' });
    res.status(200).json({ user, token });
  } catch (error) {
    console.error(error); // 打印错误信息，方便调试
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

const topUp = async (req, res) => {
  try {
    let amount = Number(req.body.amount);
    if (isNaN(amount) || amount <= 0) {
      return res.status(400).json({ error: 'Invalid amount' });
    }

    const userId = req.user.id;
    
    // 直接更新数据库
    await UserModel.updateVirtualCurrency(userId, amount);
    
    // 从数据库获取最新用户数据
    const updatedUser = await UserModel.getUserById(userId);
    
    if (!updatedUser) {
      return res.status(404).json({ error: 'User not found' });
    }

    res.status(200).json({
      message: 'Top-up successful',
      balance: updatedUser.virtual_currency  // 直接使用数据库返回的最新余额
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

module.exports = { register, login, topUp };